#include "stdafx.h"
#include "hereBaseShell.h"

hereBaseShell::hereBaseShell(void)
{
}

hereBaseShell::~hereBaseShell(void)
{
}

// do shell and get the result.
int hereBaseShell::doShell_Result(char* shell, char** result)
{
	SECURITY_ATTRIBUTES sa = {0};
	STARTUPINFO si = {0};
	PROCESS_INFORMATION pi = {0};
	HANDLE hRead = NULL;
	HANDLE hWrite = NULL;
	DWORD bytesRead = 0;

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	if ( !CreatePipe(&hRead, &hWrite, &sa, 0) )
		return -1;

	memset(m_sCommand, 0, sizeof(m_sCommand));
	sprintf_s(m_sCommand, sizeof(m_sCommand), "cmd.exe /c %s", shell);

	si.cb = sizeof(STARTUPINFO);
	GetStartupInfo(&si); 
	si.hStdError = hWrite;
	si.hStdOutput = hWrite;
	si.wShowWindow = SW_HIDE;
	si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;

	if ( !CreateProcess(NULL, m_sCommand,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi) )
	{
		CloseHandle(hWrite);
		CloseHandle(hRead);
		return -1;
	}
	WaitForSingleObject(pi.hProcess, INFINITE); // important
	CloseHandle(hWrite);

	memset(m_sResbuffer, 0, sizeof(m_sResbuffer));
	while (true)
	{
		if (ReadFile(hRead, m_sResbuffer, RES_BUFLEN -1, &bytesRead, NULL) == NULL)
			break;
	}
	CloseHandle(hRead);

	*result = m_sResbuffer;

	return 0;
}
